package cn.qlin.mvc.orm.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.qlin.mvc.orm.annotation.Table;
import cn.qlin.mvc.orm.annotation.Id;
import cn.qlin.mvc.orm.annotation.OneTOMany;
import cn.qlin.mvc.orm.annotation.TableCol;

/**
 * @author 吴延麟
 * 描述：对象映射注解的操作
 * */
public class ORMAnnotationOpen {

	/**
	 * 描述：获取id到数据库键的映射
	 * */
	public static String getIdtoKey(Field field) {
		Id hqls = field.getAnnotation(Id.class);
		if(hqls==null){
			return "";
		}else if("".equals(hqls.name())){
			return field.getName();
		}else{
			return hqls.name();
		}
	}
	/**
	 * 描述：获取id主键的策略
	 * */
	public static String getIdTactics(Field field) {
		Id hqls = field.getAnnotation(Id.class);
		if(hqls==null){
			return "";
		}else{
			return hqls.tactics();
		}
	}
	/**
	 * 描述：获取非id到键
	 * */
	public static String getNonIdToKey(Field field){
		TableCol hqls = field.getAnnotation(TableCol.class);
		if(hqls==null){
			return "";
		}else if("".equals(hqls.value())){
			return field.getName();
		}else{
			return hqls.value();
		}
	}
	/**
	 * 描述：获取字段名到数据库键的映射
	 * */
	public static String getFiledNameToKey(Field field){
		TableCol hqls = field.getAnnotation(TableCol.class);
		OneTOMany onetomany = field.getAnnotation(OneTOMany.class);
		if(onetomany!=null){
			return "";
		}
		if(hqls==null){
			Id id = field.getAnnotation(Id.class);
			if(id==null){
				return "";
			}else if("".equals(id.name())){
				return field.getName();
			}else{
				return id.name();
			}
		}else if("".equals(hqls.value())){
			return field.getName();
		}else{
			return hqls.value();
		}
	}
	/**
	 * 描述：获取一对多的映射
	 * */
	public static Object getOnetoMany(Object obj,Field field){
		OneTOMany hqls = field.getAnnotation(OneTOMany.class);
		
		return hqls;
	}
	/**
	 * 描述：获取字段到数据库值的映射
	 * */
	public static Object getFiledToValue(Object obj,Field field){
		Class<?> clz = obj.getClass();
		Object object = null;
		try {
			Method method = clz.getMethod(BeanOperate.getGetMethodName(field.getName()));
			object = method.invoke(obj);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	/**
	 * 描述：获取对象名到表名的映射
	 * */
	public static String getClassToTb(Class<?> clz){
		Table hql = clz.getAnnotation(Table.class);
		if((hql!=null)&&(hql.value()!=null)){
			return hql.value();
		}else{
			String s = clz.getName().substring(clz.getName().lastIndexOf(".")+1);
			return s.toLowerCase();
		}
	}
}
